package com.zxmr.webclient.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zxmr.domain.account.AccountType;
import com.zxmr.domain.account.User;
import com.zxmr.domain.file.ResourceAction;
import com.zxmr.domain.file.ResourceLevel;
import com.zxmr.domain.service.ResourceService;

@Controller
public class FileDownload {

	@RequestMapping(value = "/file/down", method = RequestMethod.GET)
	public @ResponseBody String  download(@RequestParam("id") long id, HttpServletRequest request,HttpServletResponse response)throws Exception
	{
		if(id <= 0)return "invalid url";
		User user = (User)request.getSession().getAttribute("user");
		
		if(user == null)
			return "you are not login";
		
		com.zxmr.domain.file.File file = getFileInfo(id,user.getCompany());
		
		if(!auth(file,user))
			return "you are not authorized to down load the file";
		
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");  
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;
		
		String ctxPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/");
		ctxPath +=file.getUrl();
		System.out.println(ctxPath); 
		
		try {  
            long fileLength = new File(ctxPath).length();  
            response.setContentType("application/x-msdownload;");  
            response.setHeader("Content-disposition", "attachment; filename="  
                    + new String(file.getUrl().getBytes("utf-8"), "utf-8"));  
            response.setHeader("Content-Length", String.valueOf(fileLength));  
            bis = new BufferedInputStream(new FileInputStream(ctxPath));  
            bos = new BufferedOutputStream(response.getOutputStream());  
            byte[] buff = new byte[2048];  
            int bytesRead;  
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
                bos.write(buff, 0, bytesRead);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
    		response.setContentType("text/html;charset=utf-8");
    		request.setCharacterEncoding("UTF-8");  
        } finally {  
            if (bis != null)  
                bis.close();  
            if (bos != null)  
                bos.close();  
        }
		return null;
	}
	private com.zxmr.domain.file.File getFileInfo(long id,int company)
	{
		ResourceService service = new ResourceService();
		return service.queryFile(id, company);
	}
	private boolean auth(com.zxmr.domain.file.File file,User user)
	{
		if(file == null || user.getCompany() != file.getCompany())
			return false;
		
		// if it is in temp folder
		if(file.getParent() == 0)return false;
		
		if(user.getAccountType() == AccountType.Supervisor || user.getName().equals(file.getOwner()))
			return true;
		
		if(file.getLevel() == ResourceLevel.Private)return false;
		
		ResourceService service = new ResourceService();
		return service.isUserAuthorizedForAction(file.getParent(), user, ResourceAction.view);
	}
}
